/**
 * @author sev_user
 * SdkChord Survey
 */
package smartclass.present;

import java.util.List;

import smartclass.data.FinalValues;
import smartclass.fragment.StudentDrawFragment;
import smartclass.fragment.StudentFolderFragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.MenuItem;
import android.widget.LinearLayout;

import com.jeremyfeinstein.slidingmenu.example.R;
import com.samsung.android.sdk.SsdkUnsupportedException;
import com.samsung.android.sdk.chord.InvalidInterfaceException;
import com.samsung.android.sdk.chord.Schord;
import com.samsung.android.sdk.chord.SchordChannel;
import com.samsung.android.sdk.chord.SchordManager;
import com.samsung.android.sdk.chord.SchordManager.NetworkListener;
import com.samsung.android.sdk.pen.Spen;
import com.samsung.android.sdk.pen.engine.SpenSurfaceView;

public class StudentActivityTest extends FragmentActivity {
	private LinearLayout tvFolderManager;
	private SchordChannel channel = null;
	private String fromChannelS = null;
	public static SchordManager mSchordManger;
	private int mSelectedInterface = -1;
	public static SpenSurfaceView mSpenSurfaceView;
	private Context mContext;
	private boolean isFeatureSpen = false;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.student_activity);
		// tvFolderManager = (LinearLayout)
		// findViewById(R.id.tvDirectionFolderManager);
		// tvFolderManager.setEnabled(false);
		mContext = StudentActivityTest.this;
		Spen spen = new Spen();
		try {
			spen.initialize(mContext);
			isFeatureSpen = spen.isFeatureEnabled(Spen.DEVICE_PEN);
		} catch (SsdkUnsupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			finish();
		}
		mSpenSurfaceView = new SpenSurfaceView(mContext);
		if (mSpenSurfaceView == null) {
			FinalValues.displayNotification(mContext,
					"Cannot creat SurfaceView");
			finish();
		}

		/*
		 * Chord
		 */
		initChord();
		startChord();
		FragmentTransaction fragment = getSupportFragmentManager()
				.beginTransaction();
//		fragment.replace(R.id.layoutStudent, new StudentDrawFragment(this));
		fragment.commit();

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (item.getItemId() == android.R.id.home) {
			FragmentTransaction fragment = getSupportFragmentManager()
					.beginTransaction();
			// fragment.replace(R.id.layoutStudent,
			// new StudentFolderFragment(this));
			fragment.addToBackStack(StudentActivityTest.class.toString());
			fragment.commit();
			tvFolderManager.setEnabled(true);

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		stopChord();
		if (mSchordManger != null) {
			mSchordManger.close();
			mSchordManger = null;
		}
		super.onDestroy();
	}

	private void initChord() {

		// -----------------------------init Chord--------------------------
		Schord chord = new Schord();
		try {
			/*************** Kiem tra dieu kien cua chord *************/
			chord.initialize(this);
		} catch (SsdkUnsupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}
		if (mSchordManger == null) {
			mSchordManger = new SchordManager(this);
		}
		FinalValues.displayNotification(StudentActivityTest.this, "IP: "
				+ mSchordManger.getIp());
		System.out.println("Ip: " + mSchordManger.getIp());
		mSchordManger.setLooper(getMainLooper());
		mSchordManger.setNetworkListener(new NetworkListener() {

			@Override
			public void onDisconnected(int interfaceType) {
				// TODO Auto-generated method stub
				if (interfaceType == mSelectedInterface) {
					FinalValues.displayNotification(StudentActivityTest.this,
							"is disconnect");
				}
			}

			@Override
			public void onConnected(int interfaceType) {
				// TODO Auto-generated method stub
				if (interfaceType == mSelectedInterface) {
					FinalValues.displayNotification(StudentActivityTest.this,
							"is connected");
				}
			}
		});

	}

	private void startChord() {

		// ---------------------------------Start Chord-------------------------
		List<Integer> interfaceList = mSchordManger
				.getAvailableInterfaceTypes();
		if (interfaceList.isEmpty()) {
			System.out.println("there is no available connection");
			return;
		}

		try {

			mSchordManger.start(interfaceList.get(0).intValue(),
					mManagerListener);

		} catch (InvalidInterfaceException e) {
			// TODO Auto-generated catch block
			System.out.println("Can not start Schord!");
			e.printStackTrace();
		}

	}

	public void stopChord() {
		if (mSchordManger == null)
			return;
		mSchordManger.setNetworkListener(null);

		System.out.println("Stop Chord");
		mSchordManger.stop();
	}

	// Listener for Chord manager events
	private SchordManager.StatusListener mManagerListener = new SchordManager.StatusListener() {

		@Override
		public void onStopped(int reason) {
			// TODO Auto-generated method stub
			if (STOPPED_BY_USER == reason) {
				// Call when Chord is stopped
				System.out.println("Stop by user");
			} else if (reason == NETWORK_DISCONNECTED) {
				System.out.println("Stop by network disconnect");
			}

		}

		@Override
		public void onStarted(String name, int reason) {
			// TODO Auto-generated method stub
			if (STARTED_BY_USER == reason) {
				System.out.println("Connect with Name:" + name);
				joinChannel();
			} else if (reason == STARTED_BY_RECONNECTION) {
				System.out.println("Reconnect with name:" + name);
			}
		}
	};

	private void joinChannel() {

		System.out.println("JoinChannel");
		channel = mSchordManger.joinChannel(
				FinalValues.CHORD_HELLO_TEST_CHANNEL, mChannelListener);

		if (channel == null) {
			System.out.println("Fail to joinChannel");
			return;
		}
	}

	private SchordChannel.StatusListener mChannelListener = new SchordChannel.StatusListener() {

		@Override
		public void onNodeLeft(String fromNode, String fromChannel) {
			// TODO Auto-generated method stub
			System.out.println("Node Left: " + fromNode);

		}

		@Override
		public void onNodeJoined(String fromNode, String fromChannel) {
			// TODO Auto-generated method stub
			byte[][] payload = new byte[1][];
			payload[0] = "Hello Chord A!".getBytes();
			fromChannelS = fromChannel;
			SchordChannel channel = mSchordManger.getJoinedChannel(fromChannel);
			channel.sendData(fromNode, FinalValues.CHORD_SAMPLE_MESSAGE_TYPE,
					payload);
			System.out.println("Node join: " + fromNode);
		}

		@Override
		public void onMultiFilesWillReceive(String arg0, String arg1,
				String arg2, String arg3, int arg4, String arg5, long arg6) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onMultiFilesSent(String arg0, String arg1, String arg2,
				String arg3, int arg4, String arg5) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onMultiFilesReceived(String arg0, String arg1, String arg2,
				String arg3, int arg4, String arg5, long arg6, String arg7) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onMultiFilesFinished(String arg0, String arg1, String arg2,
				int arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onMultiFilesFailed(String arg0, String arg1, String arg2,
				String arg3, int arg4, int arg5) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onMultiFilesChunkSent(String arg0, String arg1,
				String arg2, String arg3, int arg4, String arg5, long arg6,
				long arg7, long arg8) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onMultiFilesChunkReceived(String arg0, String arg1,
				String arg2, String arg3, int arg4, String arg5, long arg6,
				long arg7) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onFileWillReceive(String arg0, String arg1, String arg2,
				String arg3, String arg4, String arg5, long arg6) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onFileSent(String arg0, String arg1, String arg2,
				String arg3, String arg4, String arg5) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onFileReceived(String arg0, String arg1, String arg2,
				String arg3, String arg4, String arg5, long arg6, String arg7) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onFileFailed(String arg0, String arg1, String arg2,
				String arg3, String arg4, int arg5) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onFileChunkSent(String arg0, String arg1, String arg2,
				String arg3, String arg4, String arg5, long arg6, long arg7,
				long arg8) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onFileChunkReceived(String arg0, String arg1, String arg2,
				String arg3, String arg4, String arg5, long arg6, long arg7) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onDataReceived(String fromNode, String fromChannle,
				String payoadType, byte[][] payload) {
			// TODO Auto-generated method stub
			if (payoadType.equals(FinalValues.CHORD_SAMPLE_MESSAGE_TYPE)) {

				System.out.println("Data Receive: from: " + fromNode
						+ "   said:" + new String(payload[0]));
				String message = new String(payload[0]);
				if (message.startsWith("NC")) {
					Log.e("Tag", message);
					Intent intent = new Intent(StudentActivityTest.this,
							TeacherActivity.class);
					startActivity(intent);
				}
			}

		}
	};

}
